import Router from '@koa/router';
const router = new Router();
import { hashPassword } from '../utils/bcrypt/index.js';
import userServices from '../controllers/index.js';
import { sign } from '../utils/jwt/index.js';
import { verify } from '../utils/jwt/index.js';

router.prefix('/user');

// 注册
router.post('/register', async (ctx, next) => {
  const { username, password, nickname } = ctx.request.body;
  const hashedPassword = await hashPassword(password);
  try {
    const res = await userServices.userRegister(
      username,
      hashedPassword,
      nickname
    );
    ctx.body = {
      code: 200,
      message: '注册成功',
      data: res,
    };
  } catch (error) {
    // 处理特定错误
    if (
      error.message === '用户名已被注册' ||
      error.message === '该昵称已被使用'
    ) {
      ctx.body = {
        code: 401,
        message: error.message,
        data: null,
      };
    } else {
      ctx.body = {
        code: 500,
        message: '服务器内部错误',
        data: null,
      };
    }
  }
});

// 登录
router.post('/login', async (ctx, next) => {
  const { username, password } = ctx.request.body;

  try {
    // 直接调用userLogin函数，它会返回用户信息或抛出错误
    const userInfo = await userServices.userLogin(username, password);
    const token = sign({
      id: userInfo.id,
      username: userInfo.username,
    });

    // 构造返回数据
    const data = {
      token,
    };

    ctx.body = {
      code: 200,
      message: '登录成功',
      data: data,
    };
  } catch (error) {
    // 处理特定错误
    if (error.message === '用户不存在' || error.message === '密码错误') {
      ctx.body = {
        code: 401,
        message: '用户名或密码错误',
        data: null,
      };
    } else {
      // 处理其他错误
      console.error('登录错误:', error);
      ctx.body = {
        code: 500,
        message: '服务器内部错误',
        data: null,
      };
    }
  }
});

// 获取用户信息
router.post('/userInfo', verify(), async (ctx, next) => {
  try {
    const res = await userServices.getUserInfo(ctx.user_id);
    const userInfo = res[0];
    const data = {
      id: ctx.user_id,
      ...userInfo,
    };
    ctx.body = {
      code: 200,
      message: '获取用户信息成功',
      data: data,
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      data: null,
    };
  }
});

// 更新用户信息
router.post('/updateUserInfo', verify(), async (ctx, next) => {
  const { name, username } = ctx.request.body;
  try {
    const res = await userServices.updateUserInfo(ctx.user_id, name, username);
    ctx.body = {
      code: 200,
      message: '更新成功',
      data: null,
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      data: null,
    };
  }
});

export default router;
